# -*- coding: utf-8 -*-
# @Time    : 2024/11/10 13:50
# @Author  : CHNJX
# @File    : response_handler.py
# @Desc    : 统一响应结构
from flask import jsonify, current_app
from functools import wraps
import traceback


def response_with_handler(f):
    """统一响应处理装饰器"""

    @wraps(f)
    def decorated(*args, **kwargs):
        try:
            result = f(*args, **kwargs)
            # 如果返回的是元组(响应, 状态码)
            if isinstance(result, tuple):
                data, status_code = result
            else:
                data, status_code = result, 200

            # 如果是错误响应，记录日志
            if isinstance(data, dict) and data.get('code', 200) != 200:
                current_app.logger.error(
                    f"API错误 - 端点: {f.__name__}, "
                    f"状态码: {data.get('code')}, "
                    f"消息: {data.get('message')}"
                )

            return jsonify({
                'code': 200,
                'message': 'success',
                'data': data
            }), status_code

        except Exception as e:
            # 获取完整的错误堆栈
            error_stack = traceback.format_exc()
            # 记录详细错误日志
            current_app.logger.error(
                f"API异常 - 端点: {f.__name__}\n"
                f"错误类型: {type(e).__name__}\n"
                f"错误信息: {str(e)}\n"
                f"堆栈跟踪:\n{error_stack}"
            )
            
            return jsonify({
                'code': 200,
                'message': 'success',
                'data': {
                    'code': 400,
                    'message': f'操作失败：{str(e)}',
                    'data': None
                }
            }), 200

    return decorated


def success_response(data=None, message="success"):
    """成功响应"""
    return {
        'code': 200,
        'message': message,
        'data': data
    }


def error_response(message, code=400, data=None):
    """错误响应"""
    # 记录错误日志
    current_app.logger.error(
        f"业务错误 - 状态码: {code}, 消息: {message}, 数据: {data}"
    )
    return {
        'code': code,
        'message': message,
        'data': data
    }
